<script setup>
import html2canvas from 'html2canvas'
import AMap from '@/components/AMap/AMap.vue';
import { computed, ref, watch } from 'vue';
import { debounce } from '@/utils/index.js'

const emits = defineEmits(['update:modelValue', 'getImage'])
const sltArea = ref(0)
const sltList = ref([])
const props = defineProps({
  modelValue: { type: Array, default: () => ([]) }
})
let polygon = null
let curMap = null
let mouseTool = null
let polyEditor = null
let curAMap = null
const defaultPStyle = {
  strokeColor: "#de844f",
  strokeWeight: 3,
  strokeOpacity: 1,
  fillColor: '#de844f',
  fillOpacity: 0.4,
  // 线样式还支持 'dashed'
  strokeStyle: "solid",
  // strokeStyle是dashed时有效
  // strokeDasharray: [30,10],
}
// 同步经纬度数据
watch(() => props.modelValue, (val) => {
  sltList.value = val || []
}, { immediate: true })
// 显示隐藏
const show = ref(false)
// 记录当前经纬度
const message = computed(() => {
  const res = sltList.value.map(item => (`${item.lng},${item.lat}`))
  return `当前区域：${res.join(',')}`
})
// 地图加载完成回调函数
const mapInit = (AMap, map) => {
  map.setDefaultCursor('crosshair');
  curMap = map
  curAMap = AMap
  resetMap()
}
const getResult = e => {
  sltArea.value = e?.target?.getArea && (e?.target?.getArea()) || 0
  const list = e?.target?.getPath && (e?.target?.getPath()) || []
  sltList.value = list.map(item => ({ lat: item.lat, lng: item.lng }))
}
// 监听绘制逻辑
const drawFun = function (event) {
  polygon = event.obj
  mouseTool.close()
  polyEditor = new curAMap.PolyEditor(curMap, polygon);
  // polyEditor.addAdsorbPolygons(polygon)
  polyEditor.open();
  getResult({ target: polygon })
  polyEditor.on('addnode', getResult)
  polyEditor.on('adjust', getResult)
}
const mapBox = ref()
const getImage = () => {
  const dom = mapBox.value.querySelector('canvas')
  getIdCarema(dom)
}
// 确定按钮提交最新经纬度
const ok = () => {
  getImage()
  show.value = false
  emits('update:modelValue', sltList.value)
}
// 恢复地图，数据回显
const resetMap = () => {
  if (props.modelValue.length > 0) {
    polygon = new curAMap.Polygon({
      path: props.modelValue.map(item => [item.lng, item.lat]),
      ...defaultPStyle
    });
    curMap.add(polygon)
    polyEditor = new curAMap.PolyEditor(curMap, polygon);
    // polyEditor.addAdsorbPolygons(polygon)
    polyEditor.open();
    getResult({ target: polygon })
    polyEditor.on('addnode', getResult)
    polyEditor.on('adjust', getResult)
    curMap.setFitView()
  } else {
    mouseTool = new curAMap.MouseTool(curMap)
    mouseTool.polygon({
      ...defaultPStyle
    })
    mouseTool.on('draw', drawFun)
  }
}
// 取消按钮恢复点位经纬度
const cancel = () => {
  show.value = false
  sltList.value = props.modelValue
  // mapClear()
}
// 提示组件的关闭方法
const onClose = () => {
  emits('update:modelValue', [])
}
// 清除已选择范围
const mapClear = () => {
  if (mouseTool) {
    mouseTool.off('draw', drawFun)
    mouseTool = null
  }
  sltArea.value = 0
  sltList.value = []
  polyEditor.off('addnode', getResult)
  polyEditor.off('adjust', getResult)
  polyEditor.close()
  curMap.remove(polygon)
  mouseTool = new curAMap.MouseTool(curMap)
  mouseTool.polygon({
    ...defaultPStyle
  })
  mouseTool.on('draw', drawFun)
}
// 打开地图
const openAMap = () => {
  show.value = true
}

const getIdCarema = (element) => {
  html2canvas(element, {
    backgroundColor: 'transparent',
    logging: false
  }).then(canvas => {
    const context = canvas.getContext('2d')
    // 关闭抗锯齿形
    context.mozImageSmoothingEnabled = false
    context.webkitImageSmoothingEnabled = false
    context.msImageSmoothingEnabled = false
    context.imageSmoothingEnabled = false
    // canvas转化为图片
    canvas2Image(canvas, canvas.width, canvas.height, '图片')
  })
}
const canvas2Image = (canvas, width, height) => {
  const retCanvas = document.createElement('canvas')
  const retCtx = retCanvas.getContext('2d')
  retCanvas.width = width
  retCanvas.height = height
  retCtx.drawImage(canvas, 0, 0, width, height, 0, 0, width, height)
  const base64 = retCanvas.toDataURL('image/png')
  emits('getImage', base64)
}

const addressIpt = ref(null)
const addressOpts = ref([])
const handleSearch = (e) => {
  if (!e) {
    return
  }
  debounce(() => {
    curAMap.plugin("AMap.Autocomplete", function () {
      let autoOptions = {
        city: "贵州省",
      };
      let Autocomplete = new curAMap.Autocomplete(autoOptions);
      Autocomplete.search(e, function (status, result) {
        if (status === 'complete') {
          addressOpts.value = (result?.tips || []).filter(ele => ele.name).map((ele, i) => {
            return {
              label: ele.name,
              value: i,
              location: ele.location
            }
          })
        } else {
          console.log(status);
          console.log(result);
        }
      });
    });
  })
}

const handleChange = e => {
  curMap.setCenter(addressOpts.value[e].location, false, 2000)
}
</script>

<template>
  <div class="com-full">
    <a-modal v-model:open="show" @cancel="cancel" class="custom-class" root-class-name="root-class-name" title="选择区域"
      placement="right" :destroyOnClose="true" width="50%">
      <div class="com-full" style="display: flex;gap: 10px;margin-bottom: 10px;">
        <!-- <AInput class="com-ipt" v-model:value="addressIpt" /> -->
        <a-select v-model:value="addressIpt" show-search placeholder="请输入地名搜索" class="com-ipt"
          :default-active-first-option="false" :show-arrow="false" :filter-option="false" :not-found-content="null"
          :options="addressOpts" @search="handleSearch" @change="handleChange"></a-select>
        <!-- <AButton @click="search">搜索</AButton> -->
      </div>
      <div class="map-box" ref="mapBox">
        <AMap :mapInit="mapInit" />
      </div>
      <a-alert description="在地图上点击创建区域范围，双击结束后可继续编辑区域" :message="message" type="info" show-icon
        style="margin-top: 10px;" />
      <template #footer>
        <a-button @click="mapClear" :disabled="sltArea === 0">清空</a-button>
        <a-button @click="cancel">取消</a-button>
        <a-button @click="ok" type="primary">提交</a-button>
      </template>
    </a-modal>
    <AButton type="primary" @click="openAMap">选择区域</AButton>
    <a-alert description="点击按钮选择区域" :message="message" type="info" show-icon style="margin-top: 10px;"
      v-if="props.modelValue.length > 0" closable @close="onClose" />
  </div>
</template>
<style lang="scss" scoped>
.map-box {
  width: 100%;
  height: 500px;
}
</style>